package 剑指Offer1;

public class _13最长公共子序 {


    //使用滚动数组，只有两行
    public int longestCommonSubsequence2(String text1, String text2) {
        if(text1 == null || text1.length() == 0) return 0;
        if(text2 == null || text2.length() == 0) return 0;
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();
        int[][] dp = new int[2][char2.length+1];
        for(int i=1;i<=char1.length;++i){
            int row = i & 1; //当前行
            int pre = (i-1) & 1; //上一个
            for(int j=1;j<=char2.length;++j){
                if(char1[i-1] == char2[j-1]){
                    dp[row][j] = dp[pre][j-1] + 1;
                }else{
                    dp[row][j] = Math.max(dp[row][j-1],dp[pre][j]);
                }
            }
        }
        return dp[char1.length&1][char2.length];
    }

    //使用DP
    public int longestCommonSubsequence(String text1, String text2) {
        if(text1 == null || text1.length() == 0) return 0;
        if(text2 == null || text2.length() == 0) return 0;
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();
        int[][] dp = new int[char1.length+1][char2.length+1];
        for(int i=1;i<=char1.length;++i){
            for(int j=1;j<=char2.length;++j){
                if(char1[i-1] == char2[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
                }
            }
        }
        return dp[char1.length][char2.length];
    }
}
